<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>sql执行接口 - adhoc</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="shortcut icon" href="./favicon.ico" />
    <script type="text/javascript" src="js/plugin/jquery.min.js"></script>
    <script type="text/javascript" src="js/plugin/fullscreen.js"></script>
    <script type="text/javascript" src="js/plugin/echarts/echarts.min.js"></script>
    <script type="text/javascript" src="js/plugin/echarts/charts.js"></script>
    <script type="text/javascript" src="js/plugin/tablesorter/jquery.tablesorter.js"></script>
    <script type="text/javascript" src="js/apiTest.js"></script>
    <script type="text/javascript" src="js/plugin/bootstrap-3.3.5/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/plugin/bootstrap-3.3.5/js/bootstrap-select.min.js"></script>
    <script type="text/javascript" src="js/plugin/bootstrap-3.3.5/js/defaults-zh_CN.min.js"></script>
    <script type="text/javascript" src="js/plugin/jsonview-v1.2.0/dist/jquery.jsonview.js"></script>
    <script type="text/javascript" src="js/plugin/echarts/charts.js"></script>
    <script type="text/javascript" src="js/sybn_bootstrap.js"></script>
    <script type="text/javascript" src="js/sybn_common.js"></script>
    <script type="text/javascript" src="js/sybn_desc_table.js"></script>
    <script type="text/javascript" src="js/plugin/sql/codemirror.js"></script>
    <script type="text/javascript" src="js/plugin/sql/matchbrackets.js"></script>
    <script type="text/javascript" src="js/plugin/sql/sql.js"></script>
    <script type="text/javascript" src="js/plugin/sql/show-hint.js"></script>
    <script type="text/javascript" src="js/plugin/sql/sql-hint3.js"></script>
    <script type="text/javascript" src="js/plugin/sql/sql-hint-sybn.js"></script>
    <script type="text/javascript" src="js/plugin/gzip/pako.min.js"></script>
    <script type="text/javascript" src="js/plugin/gzip/base64_gzip.js"></script>
    <script type="text/javascript" src="js/sybn_demo_sql.js"></script>
    <script type="text/javascript" src="js/plugin/clipboard/clipboard.min.js"></script>
    <link rel="stylesheet" href="css/fontawesome-4.2.0_ie7/4.2.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="js/plugin/bootstrap-3.3.5/css/bootstrap.min.css" />
    <link rel="stylesheet" href="js/plugin/bootstrap-3.3.5/css/bootstrap-select.min.css" />
    <link rel="stylesheet" href="js/plugin/jsonview-v1.2.0/dist/jquery.jsonview.css" />
    <link rel="stylesheet" href="js/plugin/tablesorter/theme.default.min.css" />
    <link rel="stylesheet" href="css/plugin/sql/codemirror.css" />
    <link rel="stylesheet" href="css/plugin/sql/show-hint.css" />
    <link rel="stylesheet" href="css/bootstrap_sybn_custom.css" />
    <link rel="stylesheet" href="css/api_test.css" />
    <style>
        .form-control.CodeMirror{height:230px; width:100%;}
        .panel_type_xs .form-control.CodeMirror{height: 95px;width:100%;}
        .sql_input_big .form-control.CodeMirror{height: 500px}
        .sql_input_big .iframe_preview {max-height: 400px;}
        .sql_input_big2 .form-control.CodeMirror{height: 800px}
        .sql_input_big2 .iframe_preview {max-height: 500px;}
        .btn-group-xs .btn.common_use_select {padding: 0px 5px; font-size: 10px; line-height: 1.0;}
        .common_use {margin-right: 10px;}
        .loading-indicator {position: absolute;top: 0;left: 0;padding: 10%;width: 100%;height: 100%;background: rgba(225, 225, 255, 0.8);display: flex;flex-direction: column;justify-content: center;align-items: center;z-index: 1000;}
        .spinner {border: 4px solid rgba(0, 0, 0, 0.1);width: 36px;height: 36px;border-radius: 50%;border-left-color: #09f;animation: spin 1s linear infinite;}
        @keyframes spin {to {transform: rotate(360deg);}}
        iframe {width: 100%;height: 100%;border: none;position: relative;z-index: 1;}
        .ai_result hr {margin-top: 0px;margin-bottom: 0px;border: 0;border-top: 1px solid #eee}
        .ai_result b {color:#337ab7}
        .ai_result .score {color:#F33}
        .action_group select.modelName {width: 140px;}
    </style>
</head>
<body>

<ul class="nav nav-tabs">
    <li><strong class="title">即席分析(adhoc)</strong></li>
    <li class="active"><a href="#p_select_gbi" data-toggle="tab" aria-expanded="false">人工智能查询</a></li>
    <li class=""><a href="#p_info" data-toggle="tab" aria-expanded="false">关于</a></li>
</ul>
<div class="tab-content">

    <div id="p_select_gbi" class="panel panel-primary tab-pane active sybn-api-demo">

        <div class="panel-heading text-primary btn-group-xs">
            <span class="p_title"> bi - AI智能问答, 当前支持查询生产环境的部分报表(T05)相关问题, 基于百炼工作流应用 </span>

            <span class="common_use floatRight">常用问题:
             <select class="btn btn-default common_use_select" title="常用问题" onchange="setGbiFun(this)">
                 <option value="">请选择</option>
                 <option value="今天哪几个渠道票房最高">今天哪几个渠道票房最高</option>
                 <option value="最近2周哪个影院票房最高">最近2周哪个影院票房最高</option>
                 <option value="最近三个月票房走势">最近三个月票房走势</option>
             </select>
             </span>
        </div>

        <div class="panel-body sybn-api-demo collapse in">

            <div class="input-group input-group-xs sql_textarea_parent">
                <textarea name="userQuery" rows="5" class="form-control" style="height:100px;">租户230319昨天哪几个省份票房最高</textarea>

                <span class="btn-group-vertical input-group-addon btn-group-xs padding0 action_group">
                    <select class="btn btn-default modelName" name="modelName">
                        <option value="qwq-plus" selected="selected">qwq-plus</option>
                        <option value="qwen-coder-plus">qwen-coder-plus</option>
                    </select>
                    <span class="btn-group-vertical input-group-addon btn-group-xs padding0">
                        <span class="btn btn-default gbiApi submit">提问</span>
                    </span>
                </span>
            </div>
            <div class="input-group input-group-xs iframe-container ai_result" style="width:100%; height:500px;">
                <div class="loading-indicator" id="loadingIndicator">
                    <div class="spinner"></div>
                    <p id="view_param">Loading...</p>
                </div>
                <span id="knowledge" rows="15"></span>
                <span><b>结果:</b></span>
                <textarea id="resultMsg" rows="20"></textarea>
                <span id="prompt"></span>
                <div id="outputTable"></div>
            </div>
        </div>
    </div>

    <div id="p_info" class="panel panel-primary tab-pane">
        <div class="panel-heading text-primary">
            <span class="p_title">关于 About</span>
        </div>
        <div class="panel-body sybn-api-demo collapse in">

            <div class="panel panel-success w100">
                <div class="panel-heading text-primary">
                    <span class="p_title">服务器状态</span>
                </div>
                <div class="panel-body sybn-api-demo collapse in">
                    <iframe title="info" class="json_iframe" src="info_vue.html?r=60"></iframe>
                </div>
            </div>

            <div class="panel panel-success w100">
                <div class="panel-heading text-primary">
                    <span class="p_title">重要更新: 2024-04-02</span>
                </div>
                <div class="panel-body collapse in change_log">
                    <p>
                        <strong>2025-01-02</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/gzip/gzip.html" target="_blank">gzip工具</a></span>
                    </p>
                    <p>
                        <strong>2024-04-02</strong><br/>
                        <span class="change_log_line">
                            <span>sql 翻译工具: </span>
                            <a href="js/plugin/mergely/examples/replace_clickhouse.html" target="_blank">to clickhouse </a> |
                            <a href="js/plugin/mergely/examples/replace_holo.html" target="_blank">to holo </a> |
                            <a href="js/plugin/mergely/examples/replace_flink.html" target="_blank">to flink </a>
                        </span>
                        <br/>
                        <span class="change_log_line">
                            <span>对比工具: </span>
                            <a href="js/plugin/mergely/examples/compare_tables.html" target="_blank">列表相似度对比 </a>
                        </span>
                    </p>
                    <p>
                        <strong>2023-05-29</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/viz/viz_java.html" target="_blank">java调用关系图</a></span>
                    </p>
                    <p>
                        <strong>2022-12-23</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/viz/viz_join.html" target="_blank">表join关系图</a></span>
                    </p>
                    <p>
                        <strong>2022-04-07</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/mergely/examples/simple.html" target="_blank">文本对比工具</a></span>
                    </p>
                    <p>
                        <strong>2020-05-26</strong><br/>
                        <span class="change_log_line"><a href="js/plugin/viz/viz_template2.html?table=dim_oristar_cmc_base_sale_channel" target="_blank">表关系图</a></span><br/>
                        <!--                        <span  class="change_log_line"><a href="js/plugin/viz/viz_template2.html?table=CINEMA.dw_pos_movie_ticket_order_collect&action=all" target="_blank">表关系图</a></span><br/>-->
                    </p>
                    <p>
                        <strong>2020-02-06</strong><br/>
                        <span class="change_log_line"><a href="sql_translate.html" target="_blank">sql转换</a></span>
                    </p>
                </div>
            </div>
        </div>
    </div>


    <div style="display: none;">
        <table summary="" id="defaultsTemplate" class="tableTemplate tablesorter tablesorter-default" style="display: none;">
            <thead class="thTemplate">
            <tr class="info textCenter"><th scope="col" style="display: none;"> </th></tr>
            </thead>
            <tbody class="trTemplate">
            <tr class="tinfo phrase_tr" data-id="#{id}"> </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
<script>
// SQL语句高亮
window.onload = function() {

    var query_api_base = getQueryString("api_base") || "";
    var query_api_mode = getQueryString("api_mode") || "";
    var query_api_query = getQueryString("api_query") || "";

    if (query_api_mode) {
        $('[name=modelName]').val(query_api_mode);
    }
    if (query_api_query) {
        $('[name=userQuery]').val(unzip(query_api_query));
    }

    $('body').on('click', '.gbiApi', function(e) {
        // 主接口地址
        var api = query_api_base + ($(this).data("api") || "api/chatbot0411/chat.do");
        var userQuery = $('[name=userQuery]').val();
        var modelName = $('[name=modelName]').val();

        var url2 = window.location.href.toString()
        url2 = changeURLPar(url2, "api_mode", modelName);
        url2 = changeURLPar(url2, "api_query", zip(userQuery));
        window.history.pushState({},0,url2);

        loadingIndicator.style.display = 'block';
        document.getElementById('view_param').innerHTML = userQuery + "<br/>思考中...";

        var button = $(this);
        button.prop('disabled', true);

        var aj = $.ajax({
          url : api,
          type : 'post',
          data : {query : userQuery, modelName: modelName},
          cache : false,
          dataType : 'json',
          async : true,
          success : function(data) {
            button.prop('disabled', false);
            if (data && data.resultMsg) {
                document.getElementById('resultMsg').value = data.resultMsg;
                document.getElementById('knowledge').innerHTML = data.knowledge;
                var inputTokens = data.inputTokens;
                var outputTokens = data.outputTokens;
                var time = dateFormatting(new Date(), "yyyy-MM-dd hh:mm:ss")
                var tkFee = " <b>inputTokens: </b>" + inputTokens + " <b>outputTokens: </b>" + outputTokens + " <b title='"+(inputTokens/1000)+"*0.0035元+"+(outputTokens/1000)+"*0.007元"+"'>费用: </b>"+ (inputTokens/1000*0.0035+outputTokens/1000*0.007).toFixed(4) +"元";
                document.getElementById('prompt').innerHTML = time + " <b>sessionId:</b>" + data.sessionId + " <b>requestId:</b>" + data.requestId + tkFee;

            } else {
                document.getElementById('resultMsg').value = "";
                document.getElementById('knowledge').innerHTML = data.knowledge;
            }


            // 显示表格
            if (data && data.resData) {
                var resData = data.resData;
                var $p = $("#outputTable");
                resetPreviewTabs($p);
                var view_id = setPreviewTabs($p);
                //格式化json
                var $jsonView = $p.find('.json_view');
                var rowsLength = resData.length;
                if (resData && resData.length <= 500) {
                    // 如果返回值在500行以内，将json格式化显示
                    $jsonView.JSONView(data);
                } else if (resData && resData.length >= 1000) {
                    // 如果返回值在1000行以上，不格式化返回值, 并仅保留最多1000行
                    resData.splice(1000, resData.length-2);
                    var jsonData = JSON.stringify(resData);
                    $jsonView.text(jsonData);
                    $jsonView.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，已禁用json格式化, 并仅保留最多1000行。</div>");
                } else {
                    // 如果返回值在500行以上，不格式化返回值，因为格式化太大json会卡死浏览器
                    var jsonData = JSON.stringify(resData);
                    $jsonView.text(jsonData);
                    $jsonView.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，已禁用json格式化。</div>");
                }

                // 显示表格
                // class=fixed
                $jsonView.after("<div id='view_table_"+view_id+"' class='iframe_preview tab-pane'><table class='table table-condensed tableTarget table-striped table-bordered table-hover margin0 tablesorter tablesorter-default'><thead><tr class='info'><th>-</th></tr></thead><tbody class='trTarget max-height200'><tr><td class='prompt'>暂无数据</td></tr></tbody></table></div>");
                var $iframe_preview = $jsonView.parent().find(".iframe_preview");
                showDatasByDataGbi(resData, $iframe_preview);
            } else {
                var $p = $("#outputTable");
                resetPreviewTabs($p);
            }
            if (data.resError) {
                 document.getElementById('prompt').innerHTML += "<br/><span class='red'>"+data.resError+"</span>"
            }
            loadingIndicator.style.display = 'none';
          },
          error : function(data) {
            button.prop('disabled', false);
            document.getElementById('resultMsg').value = `请求失败`;
            loadingIndicator.style.display = 'none';
          }
        });
    });
    $(".view_param").empty().append($(".view_param_1").clone().children());

    const loadingIndicator = document.getElementById('loadingIndicator');
    loadingIndicator.style.display = 'none';

    var panel_type = getQueryString("panel_type");
    if (panel_type == 'xs') {
        $("body").addClass("panel_type_xs")
    }
};

// 设置sql
var setGbiFun = function(t) {
        var setGbi;
        if (typeof t != 'string' && t.value != undefined) {
             setGbi = t.value;
        }
        if (!setGbi) {
            return;
        }
        var s = $('[name=gbi]').val(setGbi);
}


var showDatasByDataGbi = function(resData, $div, currentSecMills) {
    $view_div = $div.closest('.view_div');
    $view_div.find('.tab_rows').text('');
    if (resData && resData.length > 0) {
        loadDataToTable(resData, $div, "#defaultsTemplate");
        $div.find(".tablesorter").tablesorter();
        $view_div.find('.tab_view_table').click();
        var text = "返回["+resData.length+"]条结果 ";
        if (currentSecMills) {
            var currentSec = currentSecMills / 1000;
            text += (currentSec > 100 ? currentSec.toFixed(0) + "秒 " : currentSec.toFixed(2) + "秒 ");
        }

        $view_div.find('.tab_rows').text(text);
        if (resData.length <= 1000) {
            // 导出数据  为 csv 文件
            var csvDownload = $("<a href='###' title='直接导出以下表格的数据到csv文件' >导出表格</a>")
            csvDownload.on("click", function(){downloadJson2Csv(resData)});
            var csvDownloadLi = $("<li class='tab_clear' style='float:right'></li>")
            csvDownloadLi.append(csvDownload);
            $view_div.find('.tab_rows').closest('li').before(csvDownloadLi);

            // 复制到粘贴板
            var tsvDownload = $("<a href='###' title='复制以下表格的数据到粘贴板' >复制到粘贴板</a>")
            tsvDownload.on("click", function(){downloadJson2Tsv(resData)});
            var tsvDownloadLi = $("<li class='tab_clear' style='float:right'></li>")
            tsvDownloadLi.append(tsvDownload);
            $view_div.find('.tab_rows').closest('li').before(tsvDownloadLi);
        }

        var tableFixed = $("<a href='###' title='对齐列宽' >对齐列宽</a>")
        tableFixed.on("click", function(){
            $table = $view_div.find('table');
            if ($table.hasClass("tableFixed")) {
                $table.removeClass("tableFixed");
                $(this).removeClass("active");
            } else {
                $table.addClass("tableFixed");
                $(this).addClass("active");
            }
        });
        var tableFixedLi = $("<li class='tab_tableFixed' style='float:right'></li>")
        tableFixedLi.append(tableFixed);

        if (resData.length > 1000) {
            $dev.prepend("<div style='color: #900b09;border: 1px dotted #900b09;background: #FEB;'>返回值内容过大["+rowsLength+"行]，为了防止浏览器崩溃，只显示前1000条数据，如需导出大量数据，建议直接导出csv。</div>");
        }
        $view_div.find('.tab_rows').closest('li').before(tableFixedLi);

    } else {
        $div.find('.prompt').text('没有查询到数据!');
    }
}
</script>
</html>
